package com.ruoyi.pg.evaluate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.pg.answerSheet.service.IPgAnswerService;
import com.ruoyi.pg.answerSheet.vo.PgAnswerVo;
import com.ruoyi.pg.evaluate.domain.PgAssessment;
import com.ruoyi.pg.evaluate.vo.PgAssessmentVo;
import com.ruoyi.pg.evaluate.mapper.PgAssessmentMapper;
import com.ruoyi.pg.evaluate.service.IPgAssessmentService;
import com.ruoyi.pg.questionnaire.service.IPgQuestionService;
import com.ruoyi.pg.questionnaire.service.IPgSurveyService;
import com.ruoyi.pg.questionnaire.vo.PgQuestionVo;
import com.ruoyi.pg.questionnaire.vo.PgSurveyVo;
import com.ruoyi.pg.serviceTarget.service.IPgElderlyService;
import com.ruoyi.pg.serviceTarget.vo.PgElderlyVo;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.List;

/**
 * 评估Service业务层处理
 *
 * @author Ming
 * @date 2025-08-22
 */
@Service
public class PgAssessmentServiceImpl extends ServiceImpl<PgAssessmentMapper, PgAssessment> implements IPgAssessmentService {

    @Autowired
    private IPgSurveyService surveyService;
    @Autowired
    private IPgAnswerService answerService;
    @Autowired
    private IPgQuestionService questionService;
    @Autowired
    private IPgElderlyService elderlyService;

    @Override
    public TableDataInfo<PgAssessmentVo> queryList(PgAssessmentVo entity) {
        Page<PgAssessmentVo> page = this.baseMapper.queryList(PageUtils.buildPage(), entity);
        for (PgAssessmentVo record : page.getRecords()) {
            PgSurveyVo surveyVo = new PgSurveyVo();
            surveyVo.setTempId(record.getTempId());
            record.setSurveyList(surveyService.queryAll(surveyVo));
            Integer answerNum = answerService.completion(record.getId());
            record.setAnswerNum(answerNum);
            Integer questionNum = questionService.countByTempId(record.getTempId());
            record.setQuestionNum(questionNum);
            BigDecimal completion = BigDecimal.ZERO;
            if (questionNum > 0) {
                double completionRate = (double) answerNum / questionNum * 100;
                completion = BigDecimal.valueOf(completionRate).setScale(2, RoundingMode.HALF_UP);
            }
            record.setCompletion(completion);
            PgAnswerVo answerVo = answerService.queryScore(record.getId());
            if (ObjectUtil.isNotEmpty(answerVo)) {
                record.setScore(answerVo.getRemark());
                record.setAbilityLevel(answerVo.getContent());
            }
        }
        return PageUtils.buildDataInfo(page);
    }

    @Override
    public List<PgAssessmentVo> queryAll(PgAssessmentVo entity) {
        List<PgAssessmentVo> pgAssessmentVos = this.baseMapper.queryList(entity);
        for (int i = 0; i < pgAssessmentVos.size(); i++) {
            PgAssessmentVo record = pgAssessmentVos.get(i);
            // 设置序号，考虑分页情况
            record.setRowNum((i + 1));
            // 获取能力等级情况
            PgAnswerVo answerVo = answerService.queryScore(record.getId());
            if (ObjectUtil.isNotEmpty(answerVo) && ObjectUtil.isNotEmpty(answerVo.getContent())) {
                record.setAbilityLevel(answerVo.getContent());
                if ("能力完好".equals(answerVo.getContent())) record.setSelfCareLevel("自理");
                if ("能力轻度受损(轻度失能)".equals(answerVo.getContent()) || "能力中度受报(中度失能)".equals(answerVo.getContent()))
                    record.setSelfCareLevel("半自理");
                if ("能力重度受损(重度失能)".equals(answerVo.getContent()) || "能力完全丧失(完全失能)".equals(answerVo.getContent()))
                    record.setSelfCareLevel("不能自理");
            }
        }
        return pgAssessmentVos;
    }

    @Override
    public PgAssessmentVo queryById(Long id) {
        PgAssessmentVo pgAssessmentVo = this.baseMapper.queryById(id);
        if (ObjectUtil.isNotEmpty(pgAssessmentVo) && ObjectUtil.isNotEmpty(pgAssessmentVo.getTempId())) {
            PgSurveyVo surveyVo = new PgSurveyVo();
            surveyVo.setTempId(pgAssessmentVo.getTempId());
            surveyVo.setAssId(pgAssessmentVo.getId());
            pgAssessmentVo.setSurveyList(surveyService.queryAll(surveyVo));
            Integer answerNum = answerService.completion(pgAssessmentVo.getId());
            pgAssessmentVo.setAnswerNum(answerNum);
            Integer questionNum = questionService.countByTempId(pgAssessmentVo.getTempId());
            pgAssessmentVo.setQuestionNum(questionNum);
            BigDecimal completion = BigDecimal.ZERO;
            if (questionNum > 0) {
                double completionRate = (double) answerNum / questionNum * 100;
                completion = BigDecimal.valueOf(completionRate).setScale(2, RoundingMode.HALF_UP);
            }
            pgAssessmentVo.setCompletion(completion);
        }
        return pgAssessmentVo;
    }

    @Override
    public boolean insertAssessment(PgAssessmentVo entity) {
        // 查询当前最新一条的编号信息
        Long no = baseMapper.selectNo();
        if (ObjectUtil.isEmpty(no)) {
            no = 1001L;
        } else {
            no = no + 1;
        }
        entity.setNo(no);
        boolean save = save(entity);
        // 插入评估编号信息
        PgQuestionVo pgQuestionVo = questionService.queryByTempId(entity.getTempId());
        if (ObjectUtil.isNotEmpty(pgQuestionVo)) {
            String generateString = answerService.generateString(entity.getNo(), pgQuestionVo.getId());
            PgAnswerVo answerVo = new PgAnswerVo();
            answerVo.setAssId(entity.getId());
            answerVo.setSurveyId(pgQuestionVo.getSurveyId());
            answerVo.setQuestionId(pgQuestionVo.getId());
            answerVo.setContent(generateString);
            answerService.addOrEdit(answerVo);
        }
        // 插入人员基本档案信息
        PgQuestionVo questionVo = new PgQuestionVo();
        questionVo.setSurveyId(surveyService.selectIdByTempId(entity.getTempId()));
        List<PgQuestionVo> pgQuestionVos = questionService.queryAll(questionVo);
        // 查询人员信息
        PgElderlyVo elderlyVo = elderlyService.queryById(entity.getEvaluateId());
        if (ObjectUtil.isNotEmpty(elderlyVo)) {
            for (PgQuestionVo question : pgQuestionVos) {
                PgAnswerVo answerVo = new PgAnswerVo();
                answerVo.setAssId(entity.getId());
                answerVo.setSurveyId(question.getSurveyId());
                answerVo.setQuestionId(question.getId());
                if (question.getTitle().contains("姓名") && ObjectUtil.isNotEmpty(elderlyVo.getName())) {
                    answerVo.setContent(elderlyVo.getName());
                    answerService.addOrEdit(answerVo);
                }
                if (question.getTitle().contains("性别") && ObjectUtil.isNotEmpty(elderlyVo.getSex())) {
                    String sex = null;
                    if ("0".equals(elderlyVo.getSex())) sex = "男";
                    if ("1".equals(elderlyVo.getSex())) sex = "女";
                    answerVo.setContent(sex);
                    answerService.addOrEdit(answerVo);
                }
                if (question.getTitle().contains("出生日期") && ObjectUtil.isNotEmpty(elderlyVo.getBirthTime())) {
                    answerVo.setContent(elderlyVo.getBirthTime());
                    answerService.addOrEdit(answerVo);
                }
                if (question.getTitle().contains("身高") && ObjectUtil.isNotEmpty(elderlyVo.getHeight())) {
                    answerVo.setContent(String.valueOf(elderlyVo.getHeight()));
                    answerService.addOrEdit(answerVo);
                }
                if (question.getTitle().contains("体重") && ObjectUtil.isNotEmpty(elderlyVo.getWeight())) {
                    answerVo.setContent(String.valueOf(elderlyVo.getWeight()));
                    answerService.addOrEdit(answerVo);
                }
                if (question.getTitle().contains("民族") && ObjectUtil.isNotEmpty(elderlyVo.getNation())) {
                    String nation = null;
                    if ("汉族".equals(elderlyVo.getNation())) {
                        nation = "汉族";
                    } else {
                        nation = "少数民族";
                        answerVo.setRemark(elderlyVo.getNation());
                    }
                    answerVo.setContent(nation);
                    answerService.addOrEdit(answerVo);
                }
                if (question.getTitle().contains("公民身份号码") && ObjectUtil.isNotEmpty(elderlyVo.getIdNo())) {
                    answerVo.setContent(elderlyVo.getIdNo());
                    answerService.addOrEdit(answerVo);
                }
                if (question.getTitle().contains("婚姻状况") && ObjectUtil.isNotEmpty(elderlyVo.getMarital())) {
                    String marital = null;
                    if ("未知".equals(elderlyVo.getMarital())) {
                        marital = "未说明";
                    } else {
                        marital = elderlyVo.getMarital();
                    }
                    answerVo.setContent(marital);
                    answerService.addOrEdit(answerVo);
                }
            }
        }
        return save;
    }

    @Override
    public void exportToWord(PgAssessmentVo entity) {
        if (ObjectUtil.isEmpty(entity.getIds())) return;
        // 1. 初始化Word文档
        XWPFDocument doc = new XWPFDocument();
        // 2. 查询数据源（图片路径+表格内容）
        List<PgAssessmentVo> list = baseMapper.queryList(entity);
        // 3. 循环处理每条数据（插入图片+表格+分页）
        for (PgAssessmentVo pgAssessmentVo : list) {
            insertImageAndTable(doc, pgAssessmentVo);
            // 分页（每条数据后强制分页）
//            doc.createParagraph().createRun().setText("分页测试").setPageBreak(true);
            doc.createParagraph().createRun().setText("这是下一页的内容");

        }
        // 4. 保存文档
        try (FileOutputStream fos = new FileOutputStream("能力等级评估报告.docx")) {
            doc.write(fos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    // 核心方法：插入图片+构建表格样式
    private static void insertImageAndTable(XWPFDocument doc, PgAssessmentVo data) {
        // 1. 插入图片
        XWPFParagraph paragraph = doc.createParagraph();
        XWPFRun run = paragraph.createRun();
        try {
            run.addPicture(
                    new FileInputStream(data.getHeadLogo()),
                    XWPFDocument.PICTURE_TYPE_JPEG,
                    "image.jpg",
                    Units.toEMU(100),
                    Units.toEMU(100)
            );
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            throw new RuntimeException(e);
        }

        // 2. 构建表格样式（示例：2行3列）
        XWPFTable table = doc.createTable();
        table.setWidth("100%");
        for (int i = 0; i < 2; i++) {
            XWPFTableRow row = table.getRow(i);
            for (int j = 0; j < 3; j++) {
                XWPFTableCell cell = row.getCell(j);
                cell.setText(data.getElderName());
            }
        }
    }
}
